﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using Newtonsoft.Json.Linq;

namespace Client.Forms
{
    public partial class TopUpForm : Form
    {
        string userId;
        string tencentURL = "tencent://message/?uin={0}&Menu=yes";
        string priceURL = "http://yy.tianlai.net.cn/pricelist.json";
        string qq = "";
        List<Price> priceList = new List<Price>();

        public TopUpForm(string us_id, bool isExitApp = true)
        {
            userId = us_id;
            Managers.Manager.topUpForm = this;
            InitializeComponent();
            Init();
            this.Text = "订阅" + MyConst.StaticString.APPNAME;
            this.FormClosed += TopUpForm_FormClosed;
            if (!isExitApp)
                this.FormClosed -= TopUpForm_FormClosed;
        }

        void Init()
        {
            using(WebClient wc=new WebClient())
            {
                wc.Encoding = Encoding.UTF8;
                var str = wc.DownloadString(priceURL);
                JObject jo = JObject.Parse(str);
                var products = jo["products"];
                var contact = jo["contact"];
                for(int i = 0; i < products.Count(); i++)
                {
                    var p = new Price((string)products[i]["price"], (string)products[i]["name"], (string)products[i]["description"]);
                    priceList.Add(p);
                    listBox1.Items.Add(p.name + "：" + p.price);
                }
                qq = (string)contact["qq"];
            }
        }

        private void TopUpForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            Managers.Manager.ExitApp();
        }

        class Price
        {
            public string price { get; private set; }
            public string name { get; private set; }
            public string description { get; private set; }

            public Price(string price, string name, string description)
            {
                this.price = price;
                this.name = name;
                this.description = description;
            }
        }

        private void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            int i = listBox1.SelectedIndex;
            if (i > -1)
                textBox1.Text = priceList[i].description;
        }

        private void TextBox1_Enter(object sender, EventArgs e)
        {
            textBox1.Select(0, 0);
        }

        private void ContactButton_Click(object sender, EventArgs e)
        {
            var str = string.Format(tencentURL, qq);
            System.Diagnostics.Process.Start(str);
        }

        private void KeyTopupButton_Click(object sender, EventArgs e)
        {
            new KeyTopUpForm(userId).ShowDialog();
        }
    }
}
